<template>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">{{this.id===''?'新增':'编辑'}}</h4>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <input type="text" v-model.trim="title" placeholder="标题" class="form-control" />
        </div>
        <div class="form-group">
          <textarea
            v-model.trim="content"
            cols="30"
            style="resize:none"
            rows="2"
            placeholder="内容"
            class="form-control"
          ></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" @click="submit" class="btn btn-primary">保存</button>
        <button type="button" @click="cancel" class="btn btn-default">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import vm from "../utils/vm";
export default {
  data() {
    return {
      id: "",
      // 新闻标题
      title: "",
      // 新闻内容
      content: ""
    };
  },
  methods: {
    // 表单提交
    submit() {
      if (this.title === "" || this.content === "") {
        return alert("请输入完整的表单内容");
      }
      // 将新闻数据传递给父组件; 通过this.$emit()触发自定义事件, 从而实现将数据传递给父组件
      this.$emit(
        "getInfo",
        { id:this.id,title: this.title, content: this.content },
        false
      );
      // 1-关闭模态框
      // 2-重置表单
      this.id="";
      this.title = "";
      this.content = "";
    },
    // 取消操作
    cancel(){
        // 重置表单
        this.id="";
        this.title="";
        this.content="";
        // 隐藏模态框
        this.$emit('showModal',false);
    }
  },
  created() {
    // 监听自定义事件
    vm.$on("editInfo", info => {
      // 更新数据
      this.id = info.id;
      this.title = info.title;
      this.content = info.content;
    });
  }
};
</script>

<style>
.modal-dialog {
  position: fixed !important;
  display: block;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: auto;
}
</style>